//
//  LXSignRecordViewController.m
//  ZuLinProject
//
//  Created by bancheng on 2022/1/6.
//  Copyright © 2022 LX_App. All rights reserved.
//

#import "LXSignRecordListController.h"
#import "LXSignTableViewCell.h"
#import "LXSignContractApplyViewController.h"
#import "LXSignContractModel.h"
#import "LXSignContractDetailViewController.h"
#import "LXCarStockListViewController.h"
#import "LXRescindViewController.h"
#import "LXCarSignListTableViewCell.h"
#import "LXCustomerDeatilViewController.h"
@interface LXSignRecordListController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic) UITableView *tableView;
@property (nonatomic) NSMutableArray *data;
@property (nonatomic) NSInteger pageIndex;
@property (nonatomic) NSString *searchStr;
@property (nonatomic)LXTopSearchView *searchView;


@end

@implementation LXSignRecordListController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if (kUserDefaultForBool(kRefreshStr)) {
        kUserDefaultSetBool(NO, kRefreshStr);
        [self.tableView.mj_header beginRefreshing];
    }
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
   
    
    // 从搜索进入
    if (self.isSearch) {
        
        [self layoutCustomNav:self.view title:@"签约记录"];
        
        LXTopSearchView *searchView = [[LXTopSearchView alloc] initWithFrame:CGRectMake(0,kViewTopHeight, kScreenWidth, 70)];
        searchView.textField.placeholder = @"输入关键词查询";
        [searchView.textField becomeFirstResponder];
        [self.view addSubview:searchView];
        self.searchView = searchView;
        // 点击
        [searchView setClickBtnBlock:^(NSString * _Nonnull text) {
            self.searchStr = text;
            [self.view endEditing:YES];
            [self.tableView.mj_header beginRefreshing];
        }];
        [self isHaveEmptyData];
        
    }
    
    [self.view addSubview:self.tableView];
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([LXCarSignListTableViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([LXCarSignListTableViewCell class])];

    
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.pageIndex = 1;
        [self loadData];
        [kNotifyCenter postNotificationName:@"setSignCount" object:nil];
    }];

    if (!self.isSearch) {
        [self.tableView.mj_header beginRefreshing];
    }
    self.tableView.mj_footer = [MJRefreshBackStateFooter footerWithRefreshingBlock:^{
         self.pageIndex++;
        [self loadData];
    }];
    
    [[kNotifyCenter rac_addObserverForName:@"signListRefresh" object:nil] subscribeNext:^(NSNotification * _Nullable note) {
        [self.tableView.mj_header beginRefreshing];
    }];
    
}




- (void)loadData{
    
    NSString *url = [DOMAIN_URL stringByAppendingFormat:SigncontractPage_URL];
    
    
    
    NSMutableDictionary *dic = @{
        @"page":@(self.pageIndex),
        @"rows":@(10),
    }.mutableCopy;
    
    if (self.type != 0) {
        [dic setValue:[NSString stringWithFormat:@"%@",@(self.type)] forKey:@"type"];
    }
    if (!StringIsEmpty(self.searchStr)) {
        [dic setValue:self.searchStr forKey:@"searchKey"];
    }
    
    [MSNetworkManager getRevertUrl:url params:dic success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
        
        
        [self endRefreshing];
        
        if (isSuccess) {
            
            if ([self.tableView.mj_header isRefreshing]||self.pageIndex==1) {
                [self.data removeAllObjects];
                [self.tableView.mj_footer resetNoMoreData];
            }
            NSInteger totalPage = [resonseObj[@"total"] integerValue];
            
            NSArray *records = resonseObj[@"records"];
            
            [self.data addObjectsFromArray:[LXSignContractModel  mj_objectArrayWithKeyValuesArray:records]];
            
            
            if (self.data.count>=totalPage) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
            else {
                self.tableView.mj_footer.state = MJRefreshStateIdle;
            }
            
          
            
            
        }
        
        [self.tableView reloadData];
        
        [self isHaveEmptyData];
        
        
    } failure:^(NSUInteger code, NSString * _Nonnull message) {
        [self endRefreshing];
        [self isHaveEmptyData];
    } withShowHud:YES];
    
}
//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
//    return self.data.count;
//}
- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.data.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    LXCarSignListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LXCarSignListTableViewCell class])];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    LXSignContractModel *model = self.data[indexPath.row];
    cell.signModel = model;
    
    return cell;
    
    
//    [cell.btn9 whenTapped:^{
//        
//        
////        LXSignContractDetailViewController *vc = [[LXSignContractDetailViewController alloc] init];
////        vc.signContractModel = model;
////        [self pushToNextController:vc];
//        
//        NSInteger date = [NSString compareDate:model.sysTime withDate:model.endTime withFormat:@"yyyy-MM-dd"];
//        if(model.reNewFlag == 1){
//            if (date < 0) {
//                LXRescindViewController *vc = [[LXRescindViewController alloc] init];
//                vc.signContractId = model.signContractId;
//                vc.fromVC = @"LXSignRecordViewController";
//                [self pushToNextController:vc];
//            }
//            else if(date >= 0){
//                [self getImagesData:model];
//            }
//        }
//    }];
        
    
    return cell;
}
    
-(void)getImagesData:(LXSignContractModel *)model{
    
    
    LXSignContractApplyViewController *vc = [[LXSignContractApplyViewController alloc] init];
    LXSignContractModel *mm = model;
    mm.signCarBrand = model.carBrand;
    mm.signModel  = model.carModel;
    vc.signContractModel = mm;
    vc.type = 3;

    
    NSDictionary *dic = @{
        @"businessType":@"1",
        @"types":[NSString toJSONData:@[@"2",@"3",@"5"]],
        @"businessId":model.signContractId,
    };
    [MSNetworkManager postRevertUrl:GET_GetByBusinessId params:dic success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
        if (isSuccess) {
            
           
            NSDictionary *checkDic,*carDic,*driverDic;
            for (NSDictionary *dic in resonseObj) {
                
                if([dic[@"type"] intValue] == 2){
                    checkDic = dic;
                }
              
                else if([dic[@"type"] intValue] == 3){
                    carDic = dic;
                }
                else if([dic[@"type"] intValue] == 5){
                    driverDic = dic;
                }
            }
            // 验车单
            if (!ObjectIsEmpty(checkDic)) {
                vc.checkCarUrl = checkDic[@"path"];
            }
            // 车辆照片
            if (!ObjectIsEmpty(carDic)) {
                vc.carUrl = carDic[@"path"];
            }
            // 行驶证
            if (!ObjectIsEmpty(driverDic)) {
                vc.driverUrl = driverDic[@"path"];
            }
        }
        [self pushToNextController:vc];
        
    } failure:^(NSUInteger code, NSString * _Nonnull message) {
        [self pushToNextController:vc];
    } withShowHud:YES];
    
    
    
}
    

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    LXSignContractDetailViewController *vc = [[LXSignContractDetailViewController alloc] init];
    vc.signContractModel = self.data[indexPath.row];
    vc.fromVc = @"LXSignRecordViewController";
    [self pushToNextController:vc];
    
}





- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, self.searchView.Y_height, kScreenWidth, self.view.height) style:UITableViewStylePlain];
        if (self.isSearch) {
            _tableView.frame = CGRectMake(0, self.searchView.Y_height, ScreenWidth, kScreenHeight - self.searchView.Y_height);
        }
        else {
            _tableView.frame = CGRectMake(0, self.searchView.Y_height, ScreenWidth, kScreenHeight - 180 - kViewTopHeight);
        }
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = 196;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor colorWithHexString:@"#FAFBFC"];
        _tableView.tableFooterView = [UIView new];
//        _tableView.sectionFooterHeight = 10;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0;
        }
    }
    return _tableView;
}

- (void)isHaveEmptyData{
    if (self.data.count == 0) {
        self.tableView.startTip = YES;
        self.tableView.tipView.backgroundColor = self.tableView.backgroundColor;
        self.tableView.tipImage = [UIImage imageNamed:@"No_order_icon"];
        self.tableView.tipView.hidden = NO;
        self.tableView.scrollEnabled = YES;
    }else{
        self.tableView.tipView.hidden = YES;
        self.tableView.scrollEnabled = YES;
    }
}


- (void)endRefreshing{
    if ([self.tableView.mj_header isRefreshing]) {
        [self.tableView.mj_header endRefreshing];
    }
    if ([self.tableView.mj_footer isRefreshing]) {
        [self.tableView.mj_footer endRefreshing];
    }

}
- (NSMutableArray *)data{
    if (!_data) {
        _data = [[NSMutableArray alloc]init];
    }
    return _data;
}


@end
